package com.huayu.threadpools.lession2;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TestPC{

    static Lock lock = new ReentrantLock();;
    static Condition full = lock.newCondition();
    static Condition empty = lock.newCondition();
    private static int i =0;


    public static void main(String[] args) {
        new Thread(()->{
            try {
                TestPC.produce();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(()->{
            try {
                TestPC.consume();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }


    /**
     * 生产者
     */
    public static void produce() throws InterruptedException {
        lock.lock();
        try{

            for (;;){
                i++;
                System.out.println("增加："+ i);
                if (i >=30){
                    System.out.println("等待消费中");
                    Thread.sleep(1000);
                    full.await();
                    empty.signal();
                }
            }

        }finally {
            lock.unlock();
        }
    }


    /**
     * 消费者
     */
    public static void consume() throws InterruptedException {
        lock.lock();
        try{

            for (;;){
                i--;
                System.out.println("消费:"+ i);
                if (i <=0){
                    System.out.println("等待生产中。。。");
                    Thread.sleep(1000);
                    full.signal();
                    empty.await();
                }
            }

        } finally {
            lock.unlock();
        }
    }
}
